package com.lucene.search;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.core.SimpleAnalyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.common.JunitConsole;
import com.lucene.LuceneUtil;
import com.lucene.index.PositionField;

/**
 * @author Smile.Wu
 * @date 2016年1月18日  下午3:30:23
 */
public class IndexReaderTest extends JunitConsole {

	Directory directory = null;
	IndexReader indexReader = null;
	@Before
	public void init() throws IOException {
		directory = FSDirectory.open(new File(LuceneUtil.INDEX_FOLDER));
		indexReader = DirectoryReader.open(directory);
	}
	@After
	public void close() throws IOException {
		indexReader.close();
		directory.close();
	}
	@Test
	public void testSearch() throws IOException, ParseException {

		IndexSearcher searcher = new IndexSearcher(indexReader);

		QueryParser parser = new QueryParser(Version.LUCENE_46, PositionField.POSITION_TITLE, new SimpleAnalyzer(Version.LUCENE_46));
		
		Query query = parser.parse(PositionField.CITY_ID + ":" + 30201);
		console("query {}", query.toString());
		
		TopDocs topDocs = searcher.search(query, 10);
		
		console("total hits : {}", topDocs.totalHits);
		
	}
	
}
